package com.wu.util;

import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.util.Locale;
import java.util.regex.Pattern;

/**
 * @ClassName: KeywordUtil
 * @Author: xiaox
 * @Description: keyword 处理
 * @Date: 2022/11/2 13:53
 * @Version: 1.0
 */
@Data
public class KeywordUtil {

    final static Pattern compile = Pattern.compile("[\n`~^*()+=|{}':;'\\[\\].<>/?~%……&*（）\\\\——+|{}【】《》‘；：”“’。，,、？]");
    final static Pattern compile2 = Pattern.compile("[\\u0008|\\u000a\\u0009\\u000d|\\u000c]");
    final static Pattern compile3 = Pattern.compile("[' ']+");
    final static Pattern compile4 = Pattern.compile("[\n`~^*()+=|{}':;'\\[\\].<>/?~%……&*（）\\\\——+|{}【】《》‘；：”“’。，、？]");
    final static String pa = "（.*?）|\\(.*?\\)";

    public static String keywordSearchDeal(String keyword){
        return getString(keyword, compile);
    }
    public static String keywordSearchDealV2(String keyword){
        return getString(keyword, compile4);
    }

    private static String getString(String keyword, Pattern compile) {
        keyword = keyword.trim();
        if (StringUtils.isEmpty(keyword)) {
            keyword = "";
        } else {
            if (keyword.length() > 300) {
                keyword = keyword.substring(0, 300);
            }
            keyword = keyword.replaceAll(pa,"");
            if (isCornZn(keyword)){
                if (keyword.length() > 30) {
                    keyword = keyword.substring(0, 30);
                }
                keyword = compile.matcher(keyword).replaceAll("");
                keyword = compile2.matcher(keyword).replaceAll("");
                keyword = compile3.matcher(keyword).replaceAll("");
            }else {
                keyword = subWord(keyword);
                keyword = compile.matcher(keyword).replaceAll(" ");
                keyword = compile2.matcher(keyword).replaceAll(" ");
                keyword = compile3.matcher(keyword).replaceAll(" ");
            }

            keyword = keyword.trim();
            keyword = keyword.toLowerCase(Locale.ROOT);
        }
        return keyword;
    }

    public static boolean isCornZn(String str){
        String reg = "[\\u4e00-\\u9fa5]+";
        boolean flag = str.matches(reg);     //true
        return flag;
    }

    public static String subWord(String str) {
        String[] words = str.split("\\s+");
        int len = 30;
        if (words.length > len) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < len; i++) {
                if (i < len - 1) {
                    sb.append(words[i]).append(" ");
                } else {
                    sb.append(words[i]);
                }
            }
            return sb.toString();
        }
        return str;
    }

    public static String removeTrim(String str){
        return str.replaceAll("\\s+", " ").trim();
    }

}
